//
//  ZYCDutyBulletionRecordTableDetailViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/27.
//

#import "ZYCDutyBulletionRecordTableDetailViewController.h"
#import "ZYCDutyBulletionRecordTableDetailCell.h"
#import "ZYCDutyBulletionRecordDetailModel.h"
#import "BTImageTitleButton.h"
#import "ZYCModifyDutyRecordDetailHeaderView.h"

#import "SESSFileLookController.h"
//#import "ZYCUpdateDutyRecordViewController.h"
#import "ZYCModifyDutyRecordViewController.h"
#import "ZYCDutyRecordTipView.h"
#import "UITableView+NoData.h"
#import "ZYCTipView.h"

@interface ZYCDutyBulletionRecordTableDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIDocumentInteractionControllerDelegate>

#define kCachePath  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) BTImageTitleButton *rightButton;
@property (nonatomic, strong) ZYCDutyBulletionRecordDetailModel *detailModel;
@property (nonatomic, strong) ZYCModifyDutyRecordDetailHeaderView *headerView;
@property (nonatomic, copy) NSString *fileUrl;

@property (nonatomic, strong) ZYCDutyRecordTipView *tipView;
@property (nonatomic, strong) ZYCTipView *alertView;

@end

@implementation ZYCDutyBulletionRecordTableDetailViewController

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"详情";
    [self judgeIsKillTerminate];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    if (self.type == ZYCManageTypeDutyBulletion) {//值班报告
        [self.rightButton setTitle:@"下载" forState:UIControlStateNormal];
        [self.rightButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
    }else{// 值班记录
        [self.rightButton setTitle:@"修改" forState:UIControlStateNormal];
        [self.rightButton setImage:[UIImage imageNamed:@"xiugai"] forState:UIControlStateNormal];
    }

    [self.headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.tableView);
        make.width.mas_equalTo(kScreenWidth);
    }];
    [self.tableView layoutIfNeeded];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadDutyBulletinDeatil];
}


- (void)judgeIsKillTerminate{
    // 判断是否有杀掉进程的
    NSDictionary *params = [[NSUserDefaults standardUserDefaults] objectForKey:self.dutyplanRecordId];
    if (params){
        [[URLManager sharedURLManager] postUrlString:Appliance_Post_updateOperateStatus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            } success:^(id  _Nullable responseObject) {
                if (SUCCESS(responseObject[@"code"])) {
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey: self.dutyplanRecordId];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            } failure:^(NSError * _Nonnull error) {
            }];
    }
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.detailModel.busRecordReports.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCDutyBulletionRecordTableDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCDutyBulletionRecordTableDetailCell class]) forIndexPath:indexPath];
    cell.model = self.detailModel.busRecordReports[indexPath.row];
    return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


#pragma mark - 网络请求
//值班报告详情
- (void)loadDutyBulletinDeatil{
    NSDictionary *params = @{
        @"dutyplanRecordId":self.dutyplanRecordId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_DutyBulletinDeatil requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                self.detailModel = [ZYCDutyBulletionRecordDetailModel yy_modelWithDictionary:responseObject[@"body"]];
                    self.fileUrl = self.detailModel.busDutyplansRecord.fileUrl;
                self.headerView.model = self.detailModel.busDutyplansRecord;
                [self.tableView layoutIfNeeded];
                self.tableView.tableHeaderView = self.headerView;
                if (self.fileUrl.length == 0) {
                    [self.tableView showDataWithString:self.fileUrl];
                    return;
                }else{
                    [self.tableView reloadData];
                }
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)modifyDutyRecordStatus:(NSString *)status{
    NSDictionary *params = @{
        @"dutyplanRecordId":self.dutyplanRecordId,
        @"operateStatus":status
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_updateOperateStatus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
- (void)getOperateStatus{
    NSDictionary *params = @{
        @"dutyplanRecordId":self.dutyplanRecordId
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_GetOperateStatus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                //操作状态(1-有人操作，2-无人操作)
                if ([responseObject[@"body"] integerValue] == 2) {
                    ZYCModifyDutyRecordViewController *vc = [[ZYCModifyDutyRecordViewController alloc] init];
                    vc.dutyplanRecordId = self.dutyplanRecordId;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    [self.tipView show];
                }
            }else{

            }
        } failure:^(NSError * _Nonnull error) {
        }];
}

- (void)download{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],self.fileUrl];
    NSArray *fileArr = [self.fileUrl componentsSeparatedByString:@"/"];
    NSString *fileName = fileArr.lastObject;
    
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSessionDownloadTask *task = [[URLManager sharedURLManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"downloadProgress%f",1.0*downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *cachesPath = [kCachePath stringByAppendingPathComponent:fileName];
        return [NSURL fileURLWithPath:cachesPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
//            NSLog(@"下载成功%@",[filePath absoluteString]);
            [self openAnnex:filePath];
        }else{
//            NSLog(@"下载成功%@",error);
        }
    }];
    [task resume];
}
- (void)clickDownloadAction{
    NSArray *fileArr = [self.fileUrl componentsSeparatedByString:@"/"];
    NSString *fileName = fileArr.lastObject;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [kCachePath stringByAppendingPathComponent:fileName];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.alertView.filePath = filePath;
        [self.alertView show];
    }else{
        [self download];
    }
}

- (void)openAnnex:(NSURL *)filePath{
    if ([[filePath pathExtension] isEqualToString:@"xls"]) {
        UIDocumentInteractionController *documentController = [UIDocumentInteractionController
                                   interactionControllerWithURL:filePath];
        [documentController setDelegate:self];
        [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    }else{
        SESSFileLookController *vc = [[SESSFileLookController alloc] initWithFilePath:filePath];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

#pragma mark - getters
- (ZYCTipView *)alertView {
    if (!_alertView) {
        ZYCWeakSelf
        _alertView = [[ZYCTipView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _alertView.title = @"温馨提示";
        _alertView.content = @"是否打开文件?";
        _alertView.clickComfirmBlock = ^(NSString * _Nonnull filePath) {
            [weakSelf openAnnex:[NSURL fileURLWithPath:filePath]];
        };
        [self.navigationController.view addSubview:_alertView];
    }
    return _alertView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCDutyBulletionRecordTableDetailCell class] forCellReuseIdentifier:NSStringFromClass([ZYCDutyBulletionRecordTableDetailCell class])];
        _tableView.estimatedRowHeight = 300.0f;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (BTImageTitleButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [BTImageTitleButton buttonWithType:UIButtonTypeCustom];
        _rightButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_rightButton setTitleColor:HEX_RGB(kBgWhiteColor) forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
        _rightButton.enabled = NO;
    }
    return _rightButton;
}

- (ZYCModifyDutyRecordDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCModifyDutyRecordDetailHeaderView alloc] initWithFrame:CGRectZero];
    }
    return _headerView;
}

- (ZYCDutyRecordTipView *)tipView {
    if (!_tipView) {
        _tipView = [[ZYCDutyRecordTipView alloc] initWithFrame:self.view.bounds];
        _tipView.tipString = @"当前有其他老师在修改值班记录\n请稍后再试!";
        [self.navigationController.view addSubview:_tipView];
    }
    return _tipView;
}

#pragma mark - private method
- (void)clickRightButton:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"修改"]) {
        [self getOperateStatus];
        
//        ZYCModifyDutyRecordViewController *vc = [[ZYCModifyDutyRecordViewController alloc] init];
//        vc.dutyplanRecordId = self.dutyplanRecordId;
//        [self.navigationController pushViewController:vc animated:YES];
        
    }else{//下载
        if (self.fileUrl.length > 0) {
            self.rightButton.enabled = YES;
        }
        [self clickDownloadAction];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
